<?php


namespace app\backend\controller\v1;

use app\backend\validate\DatumValidate;
use app\common\model\Datum as DatumModel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\exception\ValidateException;
use think\facade\Filesystem;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class Datum extends BaseController
{
    /**
     * 资料列表
     *
     * @return \think\Response
     */
    public function index()
    {
        // 资料库表
        // where条件
        $where1 = input('name');//课本名称
        $where2 = input('title');//名称
        // 分页、排序等
        $page = input('page/d', 1);
        $pageSize = input('pageSize/d', 10);
        $list = DatumModel::field('*')
            ->where(function ($query) use ($where1, $where2) {
                if ($where1) {
                    $query->where('name', 'like', '%' . $where1 . '%');
                }
                if ($where2) {
                    $query->where('title', 'like', '%' . $where2 . '%');
                }
            })
            ->order('id','desc')
            ->page($page, $pageSize)
            ->select();
        $count = DatumModel::count();
        $maxpage = ceil($count / $pageSize);
        foreach ($list as &$value) {
            $value['grade_id'] = $value->grade->title;
            $value['unit_id'] = $value->unit->title;
            $value['mold_id'] = $value->mold->title;
            $value['course_id'] = $value->course->title;
            unset($value->grade);
            unset($value->unit);
            unset($value->mold);
            unset($value->course);
            $value['image'] = config("app.domain_url") . $value['image'];
            $value['video'] = config("app.domain_url") . $value['video'];
        }
        //获取列表
        return sucessMsg(200, '获取成功！', ['list' => $list, 'total' => $count, 'page' => $maxpage]);
    }


    /**
     * 显示创建轮播表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $model = new DatumModel();
        $data = input();
//        $img = $file = request()->file('image');
        try {
            validate(DatumValidate::class)->scene('create')->check($data);
//            if (empty($img)) {
//                return errMsg(422, '请上传图片呀!');
//            }
//            $saveName = Filesystem::disk('public')->putFile('/uploads', $file);
//            $data['image'] = $saveName;
//            $data['image'] = str_replace('\\', '/', $data['image']);
            if ($model->save($data)) {
                return sucessMsg(200, '创建成功！');
            }
            return errMsg(500, '创建失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update()
    {
        $id = input('id/d');
        if (empty($id)) {
            return errMsg(400, '请选择要修改的id！');
        }
        $data = input();
//        $img = $file = request()->file('image');
        try {
            validate(DatumValidate::class)->scene('update')->check($data);
//            if (!empty($img)) {
//                $saveName = Filesystem::disk('public')->putFile('/uploads', $file);
//                $data['image'] = $saveName;
//                $data['image'] = str_replace('\\', '/', $data['image']);
//            }
            if (DatumModel::update($data, ['id' => $id])) {
                return sucessMsg(200, '修改成功！');
            }
            return errMsg(500, '修改失败！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            return errMsg(400, '请选择要删除数据id！');
        }
        $data = DatumModel::find($id);
        if (empty($data)) {
            return errMsg(400, '要删除的数据为空！');
        }
        if (DatumModel::destroy($id)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(500, '删除失败！');
    }

    /**
     * 批量删除
     *
     * @param int $id
     * @return \think\Response
     */
    public function delAll()
    {
        $ids = input('ids/a', 0);
        if (empty($ids)) {
            return errMsg(400, '请选择要删除数据id！');
        }
        $data = DatumModel::find($ids);
        if (empty($data)) {
            return errMsg(400, '要删除的数据为空！');
        }
        if (DatumModel::destroy($ids)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(500, '删除失败！');
    }

    //导入
    public function importExcel()
    {
        // 获取表单上传文件
        $file[] = request()->file('file');
        try {
            validate(['file' => 'filesize:51200|fileExt:xls,xlsx'])
                ->check($file);
            $savename = \think\facade\Filesystem::putFile('topic', $file[0]);
            $fileExtendName = substr(strrchr($savename, '.'), 1);
            // 有Xls和Xlsx格式两种
            if ($fileExtendName == 'xlsx') {
                $objReader = IOFactory::createReader('Xlsx');
            } else {
                $objReader = IOFactory::createReader('Xls');
            }
            $objReader->setReadDataOnly(TRUE);
            $objPHPExcel = $objReader->load(runtime_path() . 'uploads/' . $savename);
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            $highestColumn = $sheet->getHighestColumn();   // 取得总列数
            \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
            $lines = $highestRow - 1;
            if ($lines <= 0) {
                return errMsg(400, '数据不能为空！');
            }
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {
                $data[$j - 2] = [
                    'grade' => trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue()),
                    'unit' => trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue()),
                    'mold' => trim($objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue()),
                    'course' => trim($objPHPExcel->getActiveSheet()->getCell("D" . $j)->getValue()),
                    'name' => trim($objPHPExcel->getActiveSheet()->getCell("E" . $j)->getValue()),
                    'title' => trim($objPHPExcel->getActiveSheet()->getCell("F" . $j)->getValue()),
                    'English' => trim($objPHPExcel->getActiveSheet()->getCell("G" . $j)->getValue()),
                    'American' => trim($objPHPExcel->getActiveSheet()->getCell("H" . $j)->getValue()),
                    'desc' => trim($objPHPExcel->getActiveSheet()->getCell("I" . $j)->getValue()),
                    'example' => trim($objPHPExcel->getActiveSheet()->getCell("J" . $j)->getValue()),
                    'translate' => trim($objPHPExcel->getActiveSheet()->getCell("K" . $j)->getValue()),
                    'else' => trim($objPHPExcel->getActiveSheet()->getCell("L" . $j)->getValue()),
                    'sort' => trim($objPHPExcel->getActiveSheet()->getCell("M" . $j)->getValue()),
                ];
            }
            // 创建一个新数组
            $createData = [];
            // 循环数据
            foreach ($data as $k => $v) {
                $grade = \app\common\model\Grade::where(['title' => $v['grade']])->find();
                if (empty($grade_id)) unset($data[$k]);
                $createData[$k]['grade_id'] = $grade->id;

                $unit = \app\common\model\Unit::where(['title' => $v['unit']])->find();
                if (empty($unit_id)) unset($data[$k]);
                $createData[$k]['unit_id'] = $unit->id;

                $mold = \app\common\model\Mold::where(['title' => $v['mold']])->find();
                if (empty($mold_id)) unset($data[$k]);
                $createData[$k]['mold_id'] = $mold->id;

                $course = \app\common\model\Course::where(['title' => $v['course']])->find();
                if (empty($course_id)) unset($data[$k]);
                $createData[$k]['course_id'] = $course->id;

                $name = \app\common\model\Datum::where(['name' => $v['name']])->find();
                if (empty($name)) unset($data[$k]);
                $createData[$k]['name'] = $v['name'];

                $title = \app\common\model\Datum::where(['title' => $v['title']])->find();
                if (empty($title)) unset($data[$k]);
                $createData[$k]['title'] = $v['title'];

                $English = \app\common\model\Datum::where(['English' => $v['English']])->find();
                if (empty($English)) unset($data[$k]);
                $createData[$k]['English'] = $v['English'];

                $American = \app\common\model\Datum::where(['American' => $v['American']])->find();
                if (empty($American)) unset($data[$k]);
                $createData[$k]['American'] = $v['American'];

                $desc = \app\common\model\Datum::where(['desc' => $v['desc']])->find();
                if (empty($desc)) unset($data[$k]);
                $createData[$k]['desc'] = $v['desc'];

                $example = \app\common\model\Datum::where(['example' => $v['example']])->find();
                if (empty($example)) unset($data[$k]);
                $createData[$k]['example'] = $v['example'];

                $translate = \app\common\model\Datum::where(['translate' => $v['translate']])->find();
                if (empty($translate)) unset($data[$k]);
                $createData[$k]['translate'] = $v['translate'];

                $else = \app\common\model\Datum::where(['else' => $v['else']])->find();
                if (empty($else)) unset($data[$k]);
                $createData[$k]['else'] = $v['else'];

                $sort = \app\common\model\Datum::where(['sort' => $v['sort']])->find();
                if (empty($sort)) unset($data[$k]);
                $createData[$k]['sort'] = $v['sort'];
            }
            $model = new DatumModel();
            if ($model->saveAll($createData)) {
                return sucessMsg(200, '导入成功！');
            }
            return errMsg(500, '导入失败！');
        } catch (\think\exception\ValidateException $e) {
            return errMsg(422, $e->getMessage());
        }


    }
}